package cn.tedu.service.impl;


import cn.tedu.pojo.SysBaseArea;
import cn.tedu.service.IAreaRedisCache;
import cn.tedu.util.JsonUtil;
import cn.tedu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Set;



/**
 * @author 青石
 */
@Repository
public class AreaRedisCacheImpl implements IAreaRedisCache {

    private static final String SYMBOL_ASTERISK = ":";
    @Autowired
    StringRedisTemplate template;

    @Override
    public void initCache(List<SysBaseArea> list) {
        clear();
        HashMap<Integer, SysBaseArea> map = new HashMap<>(10);
        /* 删除表中的中国字段*/
        list.remove(0);
        /*转 map 方便直接定位 父级数据*/
        for (SysBaseArea vo : list) {
            map.put(vo.getId(), vo);
        }
        for (SysBaseArea item : list) {
            StringBuilder builder = new StringBuilder(KEY_PREFIX);
            SysBaseArea temp = item;
            int i;
            for (i = 0; i < item.getType(); i++) {
                if (temp.getParentId() == 1) {
                    break;
                }
                SysBaseArea pTemp = map.get(temp.getParentId());
                builder.insert(KEY_PREFIX.length(), pTemp.getName() + SYMBOL_ASTERISK);
                temp = pTemp;
            }
            builder.append(item.getName()).append(i + 1);
            template.opsForValue().set(builder.toString(), JsonUtil.getJsonByObj(item));
        }
    }

    @Override
    public List<SysBaseArea> readsSubList(String pName, Integer pType) {
        String pattern = KEY_PREFIX + SYMBOL_ASTERISK + pName + SYMBOL_ASTERISK + (pType + 1);
        return RedisUtil.getListByLikeKeys(template,pattern,SysBaseArea.class);
    }

    @Override
    public List<SysBaseArea> readList(Integer type) {
        String pattern = KEY_PREFIX + SYMBOL_ASTERISK + type;
        return RedisUtil.getListByLikeKeys(template,pattern,SysBaseArea.class);
    }

    @Override
    public void clear() {
        Set<String> keys = template.keys(KEY_PREFIX + SYMBOL_ASTERISK);
        if (keys != null && keys.size() > 0) {
            template.delete(keys);
        }
    }
}
